package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/11 15:11
 * https://leetcode-cn.com/problems/target-sum/
 */
public class Title494 {

    /**
     * 0-1背包问题
     * dp[j]表示装满容量为j的背包所需要的方案数
     * 递推公式：dp[j] += dp[j-nums[i]]
     * 初始化：dp[0] = 1
     * @param nums
     * @param target
     * @return
     */
    public static int findTargetSumWays(int[] nums, int target) {
        int sum = 0;
        for(int i = 0; i < nums.length; i++){
            sum += nums[i];
        }
        if((target + sum < 0) || (sum + target) % 2 != 0){
            return 0;
        }
        target = (sum + target) / 2;
        //dp[i]表示装满容量为i的背包有几种方法
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for(int i = 0; i < nums.length; i++){
            for(int j = target; j >= nums[i]; j--){
                dp[j] += dp[j - nums[i]];
            }
        }
        return dp[target];
    }

    public static void main(String[] args) {
        int[] nums = {1};
        findTargetSumWays(nums, 1);
    }
}
